﻿using Kingdee.BOS;
using Kingdee.BOS.App.Data;
using Kingdee.BOS.BusinessEntity.BusinessFlow;
using Kingdee.BOS.BusinessEntity.CloudHealthCenter;
using Kingdee.BOS.Core;
using Kingdee.BOS.Core.Bill;
using Kingdee.BOS.Core.DynamicForm;
using Kingdee.BOS.Core.DynamicForm.PlugIn;
using Kingdee.BOS.Core.DynamicForm.PlugIn.Args;
using Kingdee.BOS.Core.Interaction;
using Kingdee.BOS.Core.Metadata;
using Kingdee.BOS.Core.Metadata.FormElement;
using Kingdee.BOS.Core.Metadata.Operation;
using Kingdee.BOS.Orm;
using Kingdee.BOS.Orm.DataEntity;
using Kingdee.BOS.ServiceHelper;
using Kingdee.BOS.Util;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
//using System.Runtime.Remoting.Contexts;
using System.Text;
using System.Threading.Tasks;

namespace DzInfo.SS.TKSY
{
    [Description("直接调拨模具、维修模具时自动记录更新模具档案履历"), HotUpdate]
    public class SaveToUpMJ : AbstractOperationServicePlugIn
    {
        public override void BeforeExecuteOperationTransaction(BeforeExecuteOperationTransaction e)
        {
            base.BeforeExecuteOperationTransaction(e);
            var obj = e.SelectedRows.Select(s => s.DataEntity).FirstOrDefault();
            if (obj == null) { return; }
            string formId = this.BusinessInfo.GetForm().Id;
            var operationNumber = this.FormOperation.Operation;
            //生产入库单
            if (formId == "PRD_INSTOCK")
            {
                if (operationNumber == "Delete")
                {
                    DynamicObjectCollection rows = obj["Entity"] as DynamicObjectCollection;
                    foreach (var row in rows)
                    {
                        int eid = Convert.ToInt32(row["id"]);
                        int mjid = GetPrdMjId(eid);
                        if (mjid > 0)
                        {
                            decimal syQty = Convert.ToDecimal(row["RealQty"]);
                            DelMjfromInstock(this.OperationResult, obj, syQty, mjid);
                        }
                    }
                }
            }
        }
        public override void AfterExecuteOperationTransaction(AfterExecuteOperationTransaction e)
        {
            base.AfterExecuteOperationTransaction(e);
            var obj = e.SelectedRows.Select(s => s.DataEntity).FirstOrDefault();
            if (obj == null) { return; }
            string formId = this.BusinessInfo.GetForm().Id;
            var operationNumber = this.FormOperation.Operation;
            string mjNumber = string.Empty;
            //生产入库单
            if (formId == "PRD_INSTOCK")
            {
                if (operationNumber == "Save")
                {
                    DynamicObjectCollection rows = obj["Entity"] as DynamicObjectCollection;
                    foreach (var row in rows)
                    {
                        int eid = Convert.ToInt32(row["id"]);
                        int mjid = GetPrdMjId(eid);
                        if (mjid > 0)
                        {
                            decimal syQty = Convert.ToDecimal(row["RealQty"]);
                            ReSaveMJfromInstock(this.OperationResult, obj, mjid, syQty);
                        }
                    }
                }
                //if (operationNumber == "Delete")
                //{
                //    DynamicObjectCollection rows = obj["Entity"] as DynamicObjectCollection;
                //    foreach (var row in rows)
                //    {
                //        int eid = Convert.ToInt32(row["id"]);
                //        int mjid = GetPrdMjId(eid);
                //        if (mjid > 0)
                //        {
                //            decimal syQty = Convert.ToDecimal(row["RealQty"]);
                //            DelMjfromInstock(this.OperationResult, obj, syQty, mjid);
                //        }
                //    }
                //}
            }
            //模具维修单
            if (formId == "kfd46bce59ac14b18aa99a1d991fe2c03")
            {
                var mj = obj["F_QAYO_Base_kwj"] as DynamicObject;
                int id = mj == null ? 0 : Convert.ToInt32(mj["id"]);
                if (operationNumber == "Save")
                {
                    ReSaveMJ(id, this.OperationResult, obj, 1, null);
                }
                if (operationNumber == "Delete")
                {
                    DelMj(id, this.OperationResult, obj, 1);
                }
                //DynamicObjectCollection rows = obj["FEntity"] as DynamicObjectCollection;
                //foreach (var row in rows)
                //{
                //    var mj = row["F_rer_Base1"] as DynamicObject;
                //    int id = mj == null ? 0 : Convert.ToInt32(mj["id"]);
                //    if (operationNumber == "Save")
                //    {
                //        ReSaveMJ(id, this.OperationResult, obj, 1, row);
                //    }
                //    if (operationNumber == "Delete")
                //    {
                //        DelMj(id, this.OperationResult, obj, 1);
                //    }
                //}
            }
            //直接调拨单
            if (formId == "STK_TransferDirect")
            {
                DynamicObjectCollection rows = obj["TransferDirectEntry"] as DynamicObjectCollection;
                foreach (var row in rows)
                {
                    var mj = row["MaterialId"] as DynamicObject;
                    int id = mj == null ? 0 : Convert.ToInt32(mj["id"]);
                    DynamicObjectCollection mjIds = GetMjId(id);
                    int mjid = mjIds == null ? 0 : Convert.ToInt32(mjIds.FirstOrDefault()[0]);
                    if (operationNumber == "Save")
                    {
                        ReSaveMJ(mjid, this.OperationResult, obj, 2, row);
                    }
                    if (operationNumber == "Delete")
                    {
                        DelMj(mjid, this.OperationResult, obj, 2);
                    }
                }
            }
        }

        private void DelMjfromInstock(IOperationResult operationResult, DynamicObject obj, decimal syQty, int mjid)
        {
            //创建视图
            IBillView billView = CreateView(this.Context, "ke938e133e312458399eb8fa2e4c0a11a");
            ((IBillViewService)billView).LoadData();
            DynamicFormViewPlugInProxy eventProxy = billView.GetService<DynamicFormViewPlugInProxy>();
            eventProxy.FireOnLoad();
            billView.Model.Load(mjid);
            var objModel = billView.Model.DataObject;
            //billView.Model.CreateNewEntryRow("F_rer_Entity");
            //更新单头模具状态为使用中
            billView.Model.SetValue("FBillStatus", 1, 0);
            //原实际使用数
            decimal ysyms = Convert.ToDecimal(objModel["F_rer_Decimal2"]);
            //更新实际使用数
            billView.Model.SetValue("F_rer_Decimal2", ysyms - syQty, 0);
            //DynamicObjectCollection rows = billView.Model.DataObject["rer_Cust_Entry100101"] as DynamicObjectCollection;
            //for (int i = 0; i < rows.Count; i++)
            //{

            //    if (i == rows.Count - 1)
            //    {
            //        billView.Model.SetValue("F_rer_Date3", fdate, i);
            //        billView.Model.SetValue("F_rer_Combo1", vType, i);
            //        billView.Model.SetValue("F_rer_Text3", billno, i);
            //        billView.Model.SetValue("F_UYYX_Remark_qtr", wxjl, i);
            //        if (vType == 2)
            //        {
            //            billView.Model.SetItemValueByID("F_rer_Base2", SrcStockId, i);
            //            billView.Model.SetItemValueByID("F_rer_Base3", SrcStockId, i);
            //            //F_rer_Text8
            //            billView.Model.SetValue("F_rer_Text8", SrcStockLocId, i);
            //            //F_rer_Text7
            //            billView.Model.SetValue("F_rer_Text7", DestStockLocId, i);
            //        }
            //    }
            //}
            //billView.Model.ClearNoDataRow();
            //保存单据
            OnlySaveBill(billView, OperateOption.Create(), this.Context, operationResult);
        }

        private int GetPrdMjId(int eid)
        {
            string sql = string.Format(@"/*dialect*/ 
            SELECT T2.FMJ
            FROM T_PRD_INSTOCKENTRY T0
            JOIN T_PRD_INSTOCKENTRY_LK T1 ON T1.FENTRYID=T0.FENTRYID
            JOIN T_PRD_MOENTRY T2 ON T2.FID=T1.FSBILLID AND T2.FENTRYID=T1.FSID
            WHERE T1.FSTABLENAME='T_PRD_MOENTRY' AND T0.FENTRYID={0} ", eid);
            DynamicObjectCollection doc = DBUtils.ExecuteDynamicObject(this.Context, sql);
            if (doc.Count == 0)
            {
                return 0;
            }
            else
            {
                return Convert.ToInt32(doc[0][0]);
            }
        }

        private void ReSaveMJfromInstock(IOperationResult operationResult, DynamicObject obj, int mjid, decimal syQty)
        {
            //var fdate = DateTime.Now;
            //fdate = Convert.ToDateTime(obj["Date"]);
            //var billno = obj["BillNo"];

            //创建视图
            IBillView billView = CreateView(this.Context, "ke938e133e312458399eb8fa2e4c0a11a");
            ((IBillViewService)billView).LoadData();
            DynamicFormViewPlugInProxy eventProxy = billView.GetService<DynamicFormViewPlugInProxy>();
            eventProxy.FireOnLoad();
            billView.Model.Load(mjid);
            var objModel = billView.Model.DataObject;
            //billView.Model.CreateNewEntryRow("F_rer_Entity");
            //更新单头模具状态为使用中
            billView.Model.SetValue("FBillStatus", 1, 0);
            //原实际使用数
            decimal ysyms = Convert.ToDecimal(objModel["F_rer_Decimal2"]);
            //更新实际使用数
            billView.Model.SetValue("F_rer_Decimal2", ysyms + syQty, 0);
            //DynamicObjectCollection rows = billView.Model.DataObject["rer_Cust_Entry100101"] as DynamicObjectCollection;
            //for (int i = 0; i < rows.Count; i++)
            //{

            //    if (i == rows.Count - 1)
            //    {
            //        billView.Model.SetValue("F_rer_Date3", fdate, i);
            //        billView.Model.SetValue("F_rer_Combo1", vType, i);
            //        billView.Model.SetValue("F_rer_Text3", billno, i);
            //        billView.Model.SetValue("F_UYYX_Remark_qtr", wxjl, i);
            //        if (vType == 2)
            //        {
            //            billView.Model.SetItemValueByID("F_rer_Base2", SrcStockId, i);
            //            billView.Model.SetItemValueByID("F_rer_Base3", SrcStockId, i);
            //            //F_rer_Text8
            //            billView.Model.SetValue("F_rer_Text8", SrcStockLocId, i);
            //            //F_rer_Text7
            //            billView.Model.SetValue("F_rer_Text7", DestStockLocId, i);
            //        }
            //    }
            //}
            //billView.Model.ClearNoDataRow();
            //保存单据
            OnlySaveBill(billView, OperateOption.Create(), this.Context, operationResult);
        }

        private DynamicObjectCollection GetMjId(int id)
        {
            string sql = string.Format(@"/*dialect*/ 
            SELECT T0.FID FROM rer_t_Cust100003 T0 WHERE F_RER_MJWL={0} ", id);
            DynamicObjectCollection doc = DBUtils.ExecuteDynamicObject(this.Context, sql);
            return doc;
        }

        //public override void BeforeExecuteOperationTransaction(BeforeExecuteOperationTransaction e)
        //{
        //    base.BeforeExecuteOperationTransaction(e);
        //    var obj = e.SelectedRows.Select(s => s.DataEntity).FirstOrDefault();
        //    if (obj == null) { return; }
        //    string formId = this.BusinessInfo.GetForm().Id;
        //    var operationNumber = this.FormOperation.Operation;
        //    string mjNumber = string.Empty;
        //    //模具维修单
        //    if (formId == "kfd46bce59ac14b18aa99a1d991fe2c03")
        //    {
        //        DynamicObjectCollection rows = obj["FEntity"] as DynamicObjectCollection;
        //        foreach (var row in rows)
        //        {
        //            var mj = row["F_rer_Base1"] as DynamicObject;
        //            int id = mj == null ? 0 : Convert.ToInt32(mj["id"]);
        //            if (operationNumber == "Save")
        //            {
        //                ReSaveMJ(id, this.OperationResult, obj, 1);
        //            }
        //            if (operationNumber == "Delete")
        //            {
        //                DelMj(id, this.OperationResult, obj, 1);
        //            }
        //        }
        //    }
        //    //直接调拨单
        //    if (formId == "STK_TransferDirect")
        //    {

        //    }
        //}

        private void DelMj(int id, IOperationResult operationResult, DynamicObject obj, int v)
        {
            var billno = obj["BillNo"].ToString();
            //创建视图
            IBillView billView = CreateView(this.Context, "ke938e133e312458399eb8fa2e4c0a11a");
            ((IBillViewService)billView).LoadData();
            DynamicFormViewPlugInProxy eventProxy = billView.GetService<DynamicFormViewPlugInProxy>();
            eventProxy.FireOnLoad();
            billView.Model.Load(id);
            var objModel = billView.Model.DataObject;
            //billView.Model.CreateNewEntryRow("F_rer_Entity");

            DynamicObjectCollection rows = billView.Model.DataObject["rer_Cust_Entry100101"] as DynamicObjectCollection;
            for (int i = rows.Count - 1; i >= 0; i--)
            {
                var mjOrderNo = rows[i]["F_rer_Text3"].ToString();
                if (mjOrderNo == billno)
                {
                    billView.Model.DeleteEntryRow("F_rer_Entity", i);
                }
            }
            billView.Model.ClearNoDataRow();
            //保存单据
            OnlySaveBill(billView, OperateOption.Create(), this.Context, operationResult);
        }

        /// <summary>
        /// 初始化视图
        /// </summary>
        /// <param name="ctx">上下文</param>
        /// <param name="formId">单据标识</param>
        /// <returns></returns>
        public static IBillView CreateView(Context ctx, string formId)
        {
            FormMetadata meta = MetaDataServiceHelper.Load(ctx, formId) as FormMetadata;
            Form form = meta.BusinessInfo.GetForm();
            Type type = Type.GetType("Kingdee.BOS.Web.Import.ImportBillView,Kingdee.BOS.Web");
            var billView = (IDynamicFormViewService)Activator.CreateInstance(type);
            BillOpenParameter openParam = CreateOpenParameter(meta, ctx);
            var provider = form.GetFormServiceProvider();
            billView.Initialize(openParam, provider);
            return billView as IBillView;
        }
        /// <summary>
        /// 重新保存模具档案
        /// </summary>
        /// <exception cref="NotImplementedException"></exception>
        private void ReSaveMJ(int id, IOperationResult operationResult, DynamicObject obj, int vType, DynamicObject row)
        {
            var fdate = DateTime.Now;
            string wxjl = string.Empty;
            int SrcStockId = 0;//调出仓库
            int DestStockId = 0;//调入仓库
            string SrcStockLocId = string.Empty;
            string DestStockLocId = string.Empty;
            if (vType == 1)
            {
                fdate = Convert.ToDateTime(obj["F_rer_Date3"]);//Date
                wxjl = "维修";
            }
            if (vType == 2)
            {
                fdate = Convert.ToDateTime(obj["Date"]);//Date
                wxjl = "调拨";
                DynamicObject stock1 = row["SrcStockId"] as DynamicObject;
                SrcStockId = stock1 == null ? 0 : Convert.ToInt32(stock1["id"]);
                DynamicObject stock2 = row["DestStockId"] as DynamicObject;
                DestStockId = stock2 == null ? 0 : Convert.ToInt32(stock2["id"]);

                var cw1 = row["SrcStockLocId"] as DynamicObject;
                var cw11 = cw1[5] as DynamicObject;
                SrcStockLocId = cw11["name"].ToString();
                var cw2 = row["DestStockLocId"] as DynamicObject;
                var cw21 = cw2[5] as DynamicObject;
                DestStockLocId = cw21["name"].ToString();
            }
            var billno = obj["BillNo"];

            //创建视图
            IBillView billView = CreateView(this.Context, "ke938e133e312458399eb8fa2e4c0a11a");
            ((IBillViewService)billView).LoadData();
            DynamicFormViewPlugInProxy eventProxy = billView.GetService<DynamicFormViewPlugInProxy>();
            eventProxy.FireOnLoad();
            billView.Model.Load(id);
            var objModel = billView.Model.DataObject;
            billView.Model.CreateNewEntryRow("F_rer_Entity");
            //更新单头模具状态
            if (vType == 2)
            {
                billView.Model.SetValue("FBillStatus", 0, 0);
            }
            if (vType == 1)
            {
                billView.Model.SetValue("FBillStatus", 2, 0);
            }
            DynamicObjectCollection rows = billView.Model.DataObject["rer_Cust_Entry100101"] as DynamicObjectCollection;
            for (int i = 0; i < rows.Count; i++)
            {

                if (i == rows.Count - 1)
                {
                    billView.Model.SetValue("F_rer_Date3", fdate, i);
                    billView.Model.SetValue("F_rer_Combo1", vType, i);
                    billView.Model.SetValue("F_rer_Text3", billno, i);
                    billView.Model.SetValue("F_UYYX_Remark_qtr", wxjl, i);
                    if (vType == 2)
                    {
                        billView.Model.SetItemValueByID("F_rer_Base2", SrcStockId, i);
                        billView.Model.SetItemValueByID("F_rer_Base3", SrcStockId, i);
                        //F_rer_Text8
                        billView.Model.SetValue("F_rer_Text8", SrcStockLocId, i);
                        //F_rer_Text7
                        billView.Model.SetValue("F_rer_Text7", DestStockLocId, i);
                    }
                }
            }
            billView.Model.ClearNoDataRow();
            //保存单据
            OnlySaveBill(billView, OperateOption.Create(), this.Context, operationResult);
        }
        /// <summary>
        /// 只保存
        /// </summary>
        /// <param name="billView"></param>
        /// <param name="saveOption"></param>
        /// <param name="ctx"></param>
        public static void OnlySaveBill(IBillView billView, OperateOption saveOption, Context ctx, IOperationResult operationResult)
        {
            // 设置FormId
            Form form = billView.BillBusinessInfo.GetForm();
            if (form.FormIdDynamicProperty != null)
            {
                form.FormIdDynamicProperty.SetValue(billView.Model.DataObject, form.Id);
            }
            // 调用保存操作
            IOperationResult saveResult = BusinessDataServiceHelper.Save(
                        ctx,
                        billView.BillBusinessInfo,
                        billView.Model.DataObject,
                        saveOption,
                        "Save");
            // 显示处理结果
            if (saveResult == null)
            {
                IOperationResult opResult = new OperationResult();
                opResult.OperateResult.Add(new OperateResult()
                {
                    SuccessStatus = false,
                    Message = "未知原因导致保存失败！",
                    MessageType = Kingdee.BOS.Core.DynamicForm.MessageType.Warning,
                    Name = "保存",
                    PKValue = 0,
                });
                operationResult.MergeResult(opResult);
                //billView.ShowErrMessage("未知原因导致保存失败！");
                return;
            }
            else if (saveResult.InteractionContext != null && saveResult.InteractionContext.Option.GetInteractionFlag().Count > 0)
            {
                // 保存失败，需要用户确认问题
                InteractionUtil.DoInteraction(billView, saveResult, saveOption,
                    new Action<FormResult, IInteractionResult, OperateOption>((formResult, opResult, option) =>
                    {
                        // 用户确认完毕，重新调用保存处理
                        SaveBill(billView, option, ctx);
                    }));
            }
            operationResult.MergeResult(saveResult);
        }
        /// <summary>
        /// 保存、提交、审核单据
        /// </summary>
        /// <param name="billView">视图</param>
        /// <param name="saveOption">保存选项</param>
        /// <param name="ctx">上下文</param>
        public static void SaveBill(IBillView billView, OperateOption saveOption, Context ctx)
        {
            // 设置FormId
            Form form = billView.BillBusinessInfo.GetForm();
            if (form.FormIdDynamicProperty != null)
            {
                form.FormIdDynamicProperty.SetValue(billView.Model.DataObject, form.Id);
            }

            // 调用保存操作
            IOperationResult saveResult = BusinessDataServiceHelper.Save(
                        ctx,
                        billView.BillBusinessInfo,
                        billView.Model.DataObject,
                        saveOption,
                        "Save");
            // 显示处理结果
            if (saveResult == null)
            {
                billView.ShowErrMessage("未知原因导致保存失败！");
                return;
            }
            else if (saveResult.IsSuccess == true)
            {// 保存成功，直接显示
             //this.View.ShowOperateResult(saveResult.OperateResult);

                object[] pkArray = (from p in saveResult.SuccessDataEnity select p[0]).ToArray();

                var submitResult = BusinessDataServiceHelper.Submit(ctx, billView.BillBusinessInfo, pkArray, "Submit", OperateOption.Create());
                if (submitResult.IsSuccess)
                {
                    var auditResult = BusinessDataServiceHelper.Audit(ctx, billView.BillBusinessInfo, pkArray, OperateOption.Create());
                    if (auditResult.IsSuccess)
                    {
                        billView.ShowOperateResult(auditResult.OperateResult);
                    }
                }
            }
            else if (saveResult.InteractionContext != null && saveResult.InteractionContext.Option.GetInteractionFlag().Count > 0)
            {
                // 保存失败，需要用户确认问题
                InteractionUtil.DoInteraction(billView, saveResult, saveOption,
                    new Action<FormResult, IInteractionResult, OperateOption>((formResult, opResult, option) =>
                    {
                        // 用户确认完毕，重新调用保存处理
                        SaveBill(billView, option, ctx);
                    }));
            }
            // 保存失败，显示错误信息
            if (saveResult.IsShowMessage)
            {
                saveResult.MergeValidateErrors();
                billView.ShowOperateResult(saveResult.OperateResult);
                return;
            }
        }
        /// <summary>
        /// 初始化参数
        /// </summary>
        /// <param name="meta"></param>
        /// <param name="ctx"></param>
        /// <returns></returns>
        public static BillOpenParameter CreateOpenParameter(FormMetadata meta, Context ctx)
        {
            Form form = meta.BusinessInfo.GetForm();
            BillOpenParameter openParam = new BillOpenParameter(form.Id, meta.GetLayoutInfo().Id);
            openParam.Context = ctx;
            openParam.ServiceName = form.FormServiceName;
            openParam.PageId = Guid.NewGuid().ToString();
            openParam.FormMetaData = meta;
            openParam.Status = OperationStatus.ADDNEW;
            openParam.PkValue = null;
            openParam.CreateFrom = CreateFrom.Default;
            openParam.GroupId = "";
            openParam.ParentId = 0;
            openParam.DefaultBillTypeId = "";
            openParam.DefaultBusinessFlowId = "";
            openParam.SetCustomParameter("ShowConfirmDialogWhenChangeOrg", false);
            List<AbstractDynamicFormPlugIn> plugs = form.CreateFormPlugIns();
            openParam.SetCustomParameter(FormConst.PlugIns, plugs);
            PreOpenFormEventArgs args = new PreOpenFormEventArgs(ctx, openParam);
            foreach (var plug in plugs)
            {
                plug.PreOpenForm(args);
            }
            if (args.Cancel == true)
            {
                // 不理会插件的诉求，继续....
            }
            return openParam;
        }

        /// <summary>
        /// 加载所有列
        /// </summary>
        /// <param name="e"></param>
        public override void OnPreparePropertys(PreparePropertysEventArgs e)
        {
            base.OnPreparePropertys(e);
            FormMetadata meta = MetaDataServiceHelper.GetFormMetaData(this.Context, this.BusinessInfo.GetForm().Id);
            var fieldKeyList = meta.BusinessInfo.GetBosFields().Select(x => x.Field.Key).ToList();
            for (int i = 0; i < fieldKeyList.Count; i++)
            {
                e.FieldKeys.Add(fieldKeyList[i]);
            }
        }
    }
}
